//index.js
const app = getApp();
var api = require('../utils/util.js')
const db = wx.cloud.database();//获取云数据库引用
const dbuser = db.collection('user');//获取数据库 user 的引用
const dbimage = db.collection('question');//获取数据库 question 的引用
const dbtemp = db.collection('temp');//获取数据库 temp 的引用


Page({
  data: {
    hasUserInfo: app.globalData.hasUserInfo,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    logged: false,
    takeSession: false,
    requestResult: '',
  },

  onLoad: function () {
    if (!wx.cloud) {
      wx.redirectTo({
        url: '../chooseLib/chooseLib',
      })
      return
    }
    wx.getSetting({
      success: res =>{
       wx.getUserInfo({
         success: (res) => {
          this.setData({
            hasUserInfo: true
          })
          app.globalData.userInfo = res.userInfo;
          this.getOpenid();
         },
       }) 
      }
    })
  },
  //查询剩余次数和答题历史 | 超过7天则重置次数为2
  history: function () {
    let nowdate = (new Date()).format("Y-m-d");
  
    dbuser.where({
      openid:app.globalData.openid
    }).get().then(res =>{
      if(res.data.length == 0){
        dbuser.add({
          data:{
            openid:app.globalData.openid,
            leftTimes:2,
            lastDate:nowdate,
            history:[],
          }
        })
        app.globalData.times = 2
      }else{
        let date =  res.data[0].lastDate; 
        let pastDays = this.datedifference(date, nowdate)
        if(pastDays>=7){
          dbuser.doc(res.data[0]._id).update({
            data:{
              leftTimes:2,
              lastDate:nowdate
            }
          })
          app.globalData.times = 2
        }else{
          app.globalData.times = res.data[0].leftTimes
        }
        app.globalData.history = res.data[0].history  //将答题数据保存至全局变量
      }
    })
  },

  //计算两个时间相差天数 
  datedifference: function (sDate1, sDate2) {    //sDate1和sDate2是yyyy-mm-dd格式 
    let dateSpan,tempDate,iDays;
    sDate1 = Date.parse(sDate1);
    sDate2 = Date.parse(sDate2);
    dateSpan = sDate2 - sDate1;
    iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
    return iDays;
  },

  //开始测试  | 测试前需要先查询剩余次数
  begin: function() {  
    wx.navigateTo({
        url: '../introduce/introduce',
      })
    
    if(app.globalData.problems.length==0){
            this.loadImg('A');
            this.loadImg('B');
            this.loadImg('C');
            this.loadImg('D');
            this.loadImg('E');
       }
  },

  //加载数据库的答题选项图片数据
  loadImg:function(index){
      dbimage.where({
        group:index
      }).get().then(res =>{
          app.globalData.problems.push(res.data)
      })
  },

  //新用户，授权，获得唯一openid
  getUserInfo: function(e) {
    if (e.detail.userInfo){
      //用户按了允许授权按钮
      this.setData({
        hasUserInfo: true
      })
      app.globalData.userInfo = e.detail.userInfo
      this.getOpenid();
    } else {
      //用户按了拒绝按钮
      console.log("refuse")
    }
  },

    //通过临时数据表 temp 来获得openid
    getOpenid: function () {
    dbtemp.add({
      data:{
        nickName:app.globalData.userInfo.nickName,
      },
    }).then(res => {
      let id = res._id;
      //根据返回的记录获得openid
      dbtemp.where({
        _id: id
      }).get().then(res => {
        app.globalData.openid = res.data[0]._openid;//将openid保存至全局变量
        dbtemp.doc(res.data[0]._id).remove();  //删除该条临时记录
        this.history();
      })
    })
    }
  })